package com.lv.common.service

import android.app.*
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Binder
import android.os.Build
import android.os.Environment
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.R
import com.lv.common.event.VersionUpdataRefreshEvent
import java.io.File
import java.io.FileOutputStream
import java.net.URL
import javax.net.ssl.HttpsURLConnection
import kotlin.concurrent.thread

/**
 * 作者： ygx
 * 创建日期：2023/2/20 2:41 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class UpdataAppService : Service() {
    private lateinit var context: Context
    private var downloadFile: String = ""

    //client 可以通过Binder获取Service实例
    inner class MyBinder : Binder() {
        val service: UpdataAppService
            get() = this@UpdataAppService
    }

    //通过binder实现调用者client与Service之间的通信
    private val binder = MyBinder()
    override fun onBind(p0: Intent?): IBinder? {
        return binder
    }

    override fun onCreate() {
        super.onCreate()
        context = this
        setForground()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val stringExtra = intent?.getStringExtra("url")
        stringExtra?.let {
            thread {
                doDownLoad(stringExtra)//去下载
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }


    private fun doDownLoad(urls: String) {
        var connection: HttpsURLConnection? = null
        val url = URL(urls)
        connection = url.openConnection() as HttpsURLConnection
        connection.connectTimeout = 10000
        connection.readTimeout = 10000
        connection.requestMethod = "GET"
        val input = connection.inputStream
        val intcount = connection.contentLength//获取总长度
        val byteArray = ByteArray(1024)

        val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

        val file = File(storageDir?.absolutePath + "/" + R.string.app_name + ".apk")
        if (file.exists()) {
            file.delete()
        } else {
            file.createNewFile()
        }
        downloadFile = storageDir?.absolutePath + "/" + R.string.app_name + ".apk"
        LogUtils.e(downloadFile)
        val fos = FileOutputStream(file)
        var downLoadSize = 0;
        while (true) {
            val numread = input.read(byteArray)
            if (numread == -1) {
                break
            } else {
                fos.write(byteArray, 0, numread)
                downLoadSize += numread
                val process = ((downLoadSize.toDouble() / intcount) * 100).toInt()
                sendNotification("下载进度:${process}%")
                LiveEventBus.get(VersionUpdataRefreshEvent::class.java).post(
                    VersionUpdataRefreshEvent(process)
                )
            }
        }
        if (intcount == downLoadSize) {
            sendSuccessNotification("下载成功!")
            LogUtils.e("aaaaaaaa")
            doInstall()
        } else {
            sendNotification("下载失败!")
            if (file.exists()) {
                file.delete()
            }
            stopSelf()
        }


    }


    //开启前台服务
    private fun setForground() {
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "my_service",
                "前台Service通知",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            manager.createNotificationChannel(channel)
        }
        val notification = NotificationCompat.Builder(this, "my_service")
            .setContentTitle("开启下载")
            .setSmallIcon(R.drawable.ic_launcher)
            .build()
        startForeground(1, notification)

    }

    private fun sendNotification(msg: String) {
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "my_service",
                "前台Service通知",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            manager.createNotificationChannel(channel)
        }
        val notification = NotificationCompat.Builder(this, "my_service")
            .setContentTitle("下载")
            .setContentText(msg)
            .setSmallIcon(R.drawable.ic_launcher)
            .build()
        startForeground(2, notification)
    }


    //前台服务 这个可以进行点击跳转到安装页面
    private fun sendSuccessNotification(msg: String) {
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "my_service",
                "前台Service通知",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            manager.createNotificationChannel(channel)
        }
        var pi: PendingIntent? = null
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            pi = PendingIntent.getActivity(
                context, 0, getInstallIntent(), PendingIntent.FLAG_IMMUTABLE
            )
        } else {
            pi = PendingIntent.getActivity(
                context, 0, getInstallIntent(), PendingIntent.FLAG_ONE_SHOT
            )
        }
//        val pi = PendingIntent.getActivity(context, 0, getInstallIntent(), 0)
        val notification = NotificationCompat.Builder(this, "my_service")
            .setContentTitle("下载")
            .setContentText(msg)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pi)
            .build()
        startForeground(3, notification)
    }


    private fun getInstallIntent(): Intent {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //这里的authority是自己在AndroidManifest.xml定义的
            val apkUri = FileProvider.getUriForFile(
                context, "com.lv.suyiyong.hfr.fileProvider",
                File(downloadFile)
            )
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(
                Uri.fromFile(File(downloadFile)),
                "application/vnd.android.package-archive"
            );
        }
        return intent
    }

    private fun doInstall() {
        context.startActivity(getInstallIntent())
//        stopSelf()

    }


}